﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Configuration;
namespace LogicAndDB
{
    /// <summary>
    /// 注意，这种设计的前提是iis会自动把一个session中所有request串行化。
    /// 所以这个static才可行。
    /// </summary>
    public partial class DBContainer
    {


        public const string Name = "DBContainer";
        private static String MAIN_CONTEXT_KEY = "MainContext";
        ///应该仅在非web应用的时候发生
        private static DBContainer _nonWebInstance;


        public bool CommitChanges()
        {
            try
            {
                SaveChanges(System.Data.Objects.SaveOptions.AcceptAllChangesAfterSave);
            }
            catch (Exception ex)
            {
                return false;
            }
            return true;
        }

        public static void Init()
        {
            ConnectionString = ConfigurationManager.ConnectionStrings[Name].ToString();
        }
        /// <summary>
        /// 
        /// </summary>
        public static void RemoveContext()
        {
            if (
                HttpContext.Current != null
                &&
                HttpContext.Current.Items[MAIN_CONTEXT_KEY] != null
               )
            {
                ((DBContainer)HttpContext.Current.Items[MAIN_CONTEXT_KEY]).Dispose();
                HttpContext.Current.Items[MAIN_CONTEXT_KEY] = null;
            }

            if (_nonWebInstance != null)
            {
                _nonWebInstance.Dispose();
                _nonWebInstance = null;
            }
        }
        public static String ConnectionString
        {
            set;get;
        }
        public static DBContainer Instance
        {
             get
            {
                ///应该仅在非web应用的时候发生
                if (HttpContext.Current == null)
                {
                    if (_nonWebInstance == null)
                    {
                        _nonWebInstance = new DBContainer(ConnectionString);
                    }

                    return _nonWebInstance;
                }

                if (HttpContext.Current.Items[MAIN_CONTEXT_KEY] == null)
                {
                    HttpContext.Current.Items[MAIN_CONTEXT_KEY] = new DBContainer(ConnectionString);
                }

                return (DBContainer)HttpContext.Current.Items[MAIN_CONTEXT_KEY];
            }

         }

    }
}
